class h_lost {

	constructor() {

	}

	//获取所有失物基础信息
	async getLostDataInfo() {
		const lostInfo = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: [
				'lostPass',
				'lostFinish',
				'count(lostId) as lostCount'
			],
			group: [
				'lostPass',
				'lostFinish'
			]
		})
		let infoData = {
			lostPassCount: 0,
			lostNoPassCount: 0,
			lostWaitPassCount: 0,
			lostFinishCount: 0
		}
		for(let data of lostInfo) {
			const {lostPass, lostFinish, lostCount} = data
			if(lostFinish == 1)
				infoData.lostFinishCount += lostCount
			else if(lostPass == 0)
				infoData.lostWaitPassCount += lostCount
			else if(lostPass == 1)
				infoData.lostPassCount += lostCount
			else if(lostPass == 2)
				infoData.lostNoPassCount += lostCount
		}
		return infoData
	}

	//获取所有状态失物列表缓存
	async getAllLostListCache(start = 0, count = 10, sort = 'desc') {
		return await this.redis.system.get(`allLostList@${start}-${count}@${sort}`, true)
	}

	//获取所有状态的失物列表
	async getAllLostList(start = 0, count = 10, sort = 'desc', cache = false) {
		if(count > 100)
			return this.reject('-2088', 'get lost found record count too many')
		const lostList = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: [
				'lostId',
				'lostType',
				'lostTitle',
				'lostContent',
				'lostContact',
				'lostAddress',
				'lostFinish',
				'lostPass',
				'lostPhotoCount',
				'lostDate'
			],
			sort: {
				field: 'lostDate',
				order: sort == 'desc' ? 'desc' : 'asc'
			},
			limit: {
				start,
				count
			}
		})
		if(cache)
			await this.redis.system.set(`allLostList@${start}-${count}@${sort}`, lostList, this.config.frame.sessionExpires.lostList)
		return lostList
	}

	//获取失物列表缓存
	async getLostListCache(start = 0, count = 10, sort = 'desc') {
		return await this.redis.system.get(`lostList@${start}-${count}@${sort}`, true)
	}

	//获取失物列表
	async getLostList(start = 0, count = 10, sort = 'desc') {
		if(count > 100)
			return this.reject('-2088', 'get lost found record count too many')
		const lostList = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: [
				'lostId',
				'lostType',
				'lostTitle',
				'lostContent',
				'lostContact',
				'lostAddress',
				'lostPhotoCount',
				'lostDate'
			],
			where: 'lostFinish=0 && lostPass=1',
			sort: {
				field: 'lostDate',
				order: sort == 'desc' ? 'desc' : 'asc'
			},
			limit: {
				start,
				count
			}
		})
		await this.redis.system.set(`lostList@${start}-${count}@${sort}`, lostList, this.config.frame.sessionExpires.lostList)
		return lostList
	}

	//获取失物详情缓存
	async getLostDataCache(lostId, visitUser) {
		const lostData = await this.redis.cache.get(`lostData@${lostId}`, true)
		if(lostData) {
			if(lostData.lostPass == 0 && lostData.lostUser != visitUser)
			return this.reject('-2100', 'lost data is unaudited')
			if(lostData.lostFinish == 1 && lostData.lostUser != visitUser)
				return this.reject('-2101', 'lost data is expired')
		}
		return lostData
	}

	//获取失物详情
	async getLostData(lostId, visitUser) {
		const result = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: [
				'lostType',
				'lostUser',
				'lostTitle',
				'lostContent',
				'lostContact',
				'lostAddress',
				'lostPhotoCount',
				'lostDate',
				'lostFinish',
				'lostPass'
			],
			where: 'lostId=$lostId',
			data: {
				lostId
			}
		})
		console.log()
		if(!result || !result[0])
			return this.reject('-2099', 'lost data not found')
		const lostData = result[0]
		if((lostData.lostPass == 0 || lostData.lostPass == 2) && lostData.lostUser != visitUser)
			return this.reject('-2100', 'lost data is unaudited')
		if(lostData.lostFinish == 1 && lostData.lostUser != visitUser)
			return this.reject('-2101', 'lost data is expired')
		await this.redis.cache.set(`lostData@${lostId}`, result[0], this.config.frame.sessionExpires.lostList)
		return result[0]
	}

	//根据用户ID获取待审核记录缓存
	async getWaitRecordListByUserIdCache(userId) {
		const recordList = await this.redis.cache.get(`lostWait@${userId}`, true)
		return recordList
	}

	//根据用户ID获取待审核记录
	async getWaitRecordListByUserId(userId) {
		const recordList = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: [
				'lostId',
				'lostType',
				'lostTitle',
				'lostContent',
				'lostContact',
				'lostAddress',
				'lostPhotoCount',
				'lostPass',
				'lostDate'
			],
			where: 'lostFinish=0 && (lostPass=0 || lostPass=2) && lostUser=$lostUser',
			data: {
				lostUser: userId
			},
			sort: {
				field: 'lostDate',
				order: 'desc'
			}
		})
		await this.redis.cache.set(`lostWait@${userId}`, recordList, this.config.frame.sessionExpires.lostList)
		return recordList
	}

	//根据用户ID获取发布记录缓存
	async getPublishRecordListByUserIdCache(userId) {
		const recordList = await this.redis.cache.get(`lostPublish@${userId}`, true)
		return recordList
	}

	//根据用户ID获取发布记录
	async getPublishRecordListByUserId(userId) {
		const recordList = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: [
				'lostId',
				'lostType',
				'lostTitle',
				'lostContent',
				'lostContact',
				'lostAddress',
				'lostPhotoCount',
				'lostPassDate'
			],
			where: 'lostFinish=0 && lostPass=1 && lostUser=$lostUser',
			data: {
				lostUser: userId
			},
			sort: {
				field: 'lostPassDate',
				order: 'desc'
			}
		})
		await this.redis.cache.set(`lostPublish@${userId}`, recordList, this.config.frame.sessionExpires.lostList)
		return recordList
	}

	//根据用户ID获取完成记录缓存
	async getFinishRecordListByUserIdCache(userId) {
		const recordList = await this.redis.cache.get(`lostFinish@${userId}`, true)
		return recordList
	}

	//根据用户ID获取完成记录
	async getFinishRecordListByUserId(userId) {
		const recordList = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: [
				'lostId',
				'lostType',
				'lostTitle',
				'lostContent',
				'lostContact',
				'lostAddress',
				'lostPhotoCount',
				'lostFinishDate'
			],
			where: 'lostFinish=1 && lostPass=1 && lostUser=$lostUser',
			data: {
				lostUser: userId
			},
			sort: {
				field: 'lostFinishDate',
				order: 'desc'
			}
		})
		await this.redis.cache.set(`lostFinish@${userId}`, recordList, this.config.frame.sessionExpires.lostList)
		return recordList
	}

	//添加招领记录
	async addLostGoods(lostUser, lostTitle, lostContent, lostAddress, lostContact, uploadIdList = []) {
		const lostId = await this.common.createRandomStr(32)
		await this._handleLostPhotoIdList(lostId, uploadIdList)
		await this.mysql.cxxy.insert({
			table: 'lost_found',
			field: [
				'lostId',
				'lostType',
				'lostUser',
				'lostTitle',
				'lostContent',
				'lostAddress',
				'lostContact',
				'lostPhotoCount',
				'lostDate'
			],
			data: {
				lostId,
				lostType: 1,
				lostUser,
				lostTitle,
				lostContent,
				lostAddress,
				lostContact,
				lostPhotoCount: uploadIdList.length,
				lostDate: this.common.timestamp()
			}
		})
		await this.redis.cache.delete(`lostWait@${lostUser}`)
		return lostId
	}

	//添加失物记录
	async addLostRecord(lostUser, lostTitle, lostContent, lostAddress, lostContact, uploadIdList = []) {
		const lostId = await this.common.createRandomStr(32)
		await this._handleLostPhotoIdList(lostId, uploadIdList)
		await this.mysql.cxxy.insert({
			table: 'lost_found',
			field: [
				'lostId',
				'lostType',
				'lostUser',
				'lostTitle',
				'lostContent',
				'lostAddress',
				'lostContact',
				'lostPhotoCount',
				'lostDate'
			],
			data: {
				lostId,
				lostType: 0,
				lostUser,
				lostTitle,
				lostContent,
				lostAddress,
				lostContact,
				lostPhotoCount: uploadIdList.length,
				lostDate: this.common.timestamp()
			}
		})
		await this.redis.cache.delete(`lostWait@${lostUser}`)
		return lostId
	}

	//删除失物招领项
	async delLostData(lostId, lostUser) {
		const lostData = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: 'lostId',
			data: {
				lostId,
				lostUser
			},
			where: 'lostUser=$lostUser && lostId=$lostId'
		})
		if(!lostData || !lostData[0])
			return this.reject('-2103', 'user lost data not found')
		await this.mysql.cxxy.delete({
			table: 'lost_found',
			data: {
				lostId,
				lostUser
			},
			where: 'lostUser=$lostUser && lostId=$lostId'
		})
		await this.redis.cache.delete(`lostWait@${lostUser}`)
		await this.redis.cache.delete(`lostData@${lostId}`)
		for(let key of await this.redis.system.find('lostList@*'))
			await this.redis.system.delete(key)
		const lostPhotoPath = `${this.config.server.staticPath}/image/lost/${lostId}`
		this.fs.pathExists(lostPhotoPath, (err, exists) => {
			if(err) {
				console.error('check lost found file path failed:', err)
			}
			else if(exists) {
				this.fs.remove(lostPhotoPath, err => {
					if(err)
						console.error('remove lost found file failed:', err)
					console.log('remove lost found file success')
				})
			}
		})
		return 1
	}

	//修改失物招领审核状态
	async updateLostPassStatusFromAdmin(lostId, lostPass = 0) {
		const lostData = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: [
				'lostId',
				'lostUser'
			],
			data: {
				lostId
			},
			where: 'lostId=$lostId'
		})
		if(!lostData || !lostData[0])
			return this.reject('-2103', 'user lost data not found')
		const {lostUser} = lostData[0]
		await this.mysql.cxxy.update({
			table: 'lost_found',
			field: [
				'lostPass=$lostPass',
				'lostPassDate=$lostPassDate',
				'lostFinish=0',
				'lostFinishDate=0'
			],
			data: {
				lostId,
				lostPass: parseInt(lostPass),
				lostPassDate: lostPass == 1 || lostPass == 2 ? this.common.timestamp() : 0
			},
			where: 'lostId=$lostId'
		})
		await this.redis.cache.delete(`lostData@${lostId}`)
		await this.redis.cache.delete(`lostPublish@${lostUser}`)
		await this.redis.cache.delete(`lostFinish@${lostUser}`)
		for(let key of await this.redis.system.find('lostList@*'))
			await this.redis.system.delete(key)
		return 1
	}

	async updateLostFinishStatusFromAdmin(lostId, lostFinish = 0) {
		const lostData = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: 'lostId',
			data: {
				lostId
			},
			where: 'lostId=$lostId'
		})
		if(!lostData || !lostData[0])
			return this.reject('-2103', 'user lost data not found')
		const {lostUser} = lostData[0]
		await this.mysql.cxxy.update({
			table: 'lost_found',
			field: [
				'lostFinish=$lostFinish',
				'lostFinishDate=$lostFinishDate'
			],
			data: {
				lostId,
				lostFinish: parseInt(lostFinish),
				lostFinishDate: lostFinish == 1 ? this.common.timestamp() : 0
			},
			where: 'lostId=$lostId'
		})
		await this.redis.cache.delete(`lostData@${lostId}`)
		await this.redis.cache.delete(`lostPublish@${lostUser}`)
		await this.redis.cache.delete(`lostFinish@${lostUser}`)
		for(let key of await this.redis.system.find('lostList@*'))
			await this.redis.system.delete(key)
		return 1
	}

	async delLostDataFromAdmin(lostId) {
		const lostData = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: 'lostId',
			data: {
				lostId
			},
			where: 'lostId=$lostId'
		})
		if(!lostData || !lostData[0])
			return this.reject('-2103', 'user lost data not found')
		const {lostUser} = lostData[0]
		await this.mysql.cxxy.delete({
			table: 'lost_found',
			data: {
				lostId
			},
			where: 'lostId=$lostId'
		})
		await this.redis.cache.delete(`lostWait@${lostUser}`)
		await this.redis.cache.delete(`lostData@${lostId}`)
		for(let key of await this.redis.system.find('lostList@*'))
			await this.redis.system.delete(key)
		const lostPhotoPath = `${this.config.server.staticPath}/image/lost/${lostId}`
		this.fs.pathExists(lostPhotoPath, (err, exists) => {
			if(err) {
				console.error('check lost found file path failed:', err)
			}
			else if(exists) {
				this.fs.remove(lostPhotoPath, err => {
					if(err)
						console.error('remove lost found file failed:', err)
					console.log('remove lost found file success')
				})
			}
		})
		return 1
	}

	//修改失物招领完成状态
	async updateLostFinishStatus(lostId, lostUser, lostFinish = 0) {
		const lostData = await this.mysql.cxxy.select({
			table: 'lost_found',
			field: 'lostId',
			data: {
				lostId,
				lostUser
			},
			where: 'lostUser=$lostUser && lostId=$lostId'
		})
		if(!lostData || !lostData[0])
			return this.reject('-2103', 'user lost data not found')
		await this.mysql.cxxy.update({
			table: 'lost_found',
			field: [
				'lostFinish=$lostFinish',
				'lostFinishDate=$lostFinishDate'
			],
			data: {
				lostId,
				lostUser,
				lostFinish: parseInt(lostFinish),
				lostFinishDate: this.common.timestamp()
			},
			where: 'lostUser=$lostUser && lostId=$lostId'
		})
		await this.redis.cache.delete(`lostData@${lostId}`)
		await this.redis.cache.delete(`lostPublish@${lostUser}`)
		await this.redis.cache.delete(`lostFinish@${lostUser}`)
		for(let key of await this.redis.system.find('lostList@*'))
			await this.redis.system.delete(key)
		return 1
	}

	//处理失物图片上传
	async _handleLostPhotoIdList(lostId, uploadIdList) {
		const lostPath = `${this.config.server.basePath}/${this.config.server.staticPath}/image/lost/${lostId}`
		await this.fs.emptyDir(lostPath)
		for(let index in uploadIdList) {
			const src = `${this.config.server.basePath}/${this.config.server.tmpPath}/${uploadIdList[index]}`
			const dst = `${lostPath}/${index}.jpg`
			await this.common.moveImage(src, dst)
			await this.common.compressJpeg(dst)
		}
	}

}

module.exports = h_lost